package handlers;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import server.Webserver;

public class Contacts {
	
	public static String getContactFile() throws IOException{
    	File contacts = new File("clist");
		BufferedReader br = new BufferedReader(new FileReader(contacts));
		String line = null;
		String result = "";
		while((line = br.readLine()) != null){
			result += line;
		}
		br.close();
		return result;
    }
	
	public static HashMap<String, String> getContactList() throws IOException{
    	HashMap<String, String> aList = new HashMap<String, String>();
    	int length = getContactFile().length();
    	String src = getContactFile().substring(2, length-2);
    	String[] contacts = src.split("\\],\\[");
    	for(String c:contacts){
    		String[] s = c.split(",");
    		String s1 = s[0].substring(1,s[0].length()-1).toLowerCase();
    		String s2 = s[1].substring(1,s[1].length()-1).toLowerCase();
    		aList.put(s1, s2);
    	}
    	return aList;
    }
	
	public static String writeContacts(Webserver ws, boolean kirjutan) throws IOException{
		HashMap<String, String> cList = ws.getContacts();
		BufferedWriter fw = new BufferedWriter(new FileWriter("clist"));
		String result = "";
		int i = 1;
		int size = cList.keySet().size();
		result += "[\n";
		for(String name:cList.keySet()){
			if(i==size){
				result += "[\"" + name.toLowerCase() + "\",\"" + cList.get(name).toLowerCase() + "\"]\n";
			}else{
				result += "[\"" + name.toLowerCase() + "\",\"" + cList.get(name).toLowerCase() + "\"],\n";
			}
			i++;
		}
		result += "]";
		if(kirjutan){
			fw.write(result);	
		}
		fw.close();
		return result;
	}
	
	public static void addContact(String name, String address, int port) throws IOException{
		HashMap<String, String> contacts = getContactList();
		if(!contacts.containsValue(address+":"+port)){
			contacts.put(name, address+":"+port);
		}
	}
}
